package com.pansoft.openplanet.activity;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.util.EthTokenTransactionManager;

import net.sf.json.JSONObject;

import org.web3j.crypto.Credentials;
import org.web3j.tx.Contract;
import org.web3j.utils.Convert;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * pwr转账成功
 * Created by will on 18-3-26.
 */

public class TransferSuccessActivity extends TCBaseActivity {

    private static final String TAG = "TransferSuccessActivity";

    private TextView tvCode, tvCodeIntro, tvMyAddressIntro, tvMyAddress,
            tvToAddressIntro, tvToAddress, tvCount, tvCountUnit, tvTransStatus, tvTitle;
    private ImageView ivTranferStatus;
    private AnimationDrawable animationDrawable;
    private String myaddress;
    private String filePath;

    private String myNumber;

    private String toAccount1;
    //转账地址
    private String toAddress1;
    //转账金额
    private String count;

    private String toUserId;
    private boolean doSendMsg = false;
    private String transferTime;

    private TextView tvTime;
    private TextView tvTimeValue;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat sf1 = new SimpleDateFormat("yyyyMMddHHmmss");
    private EthTokenTransactionManager transactionManager;

//    单位 gwei
    private String gas;
    //转换后的矿工费
    private String convertGas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_activity_transfer_success);

        myaddress = getIntent().getStringExtra("myaddress");
        filePath = getIntent().getStringExtra("filePath");
        toAccount1 = getIntent().getStringExtra("toAccount");
        toAddress1 = getIntent().getStringExtra("toAddress");
        count = getIntent().getStringExtra("count");
        myNumber = EnvironmentVariable.getUserName();
        gas = getIntent().getStringExtra("gas");
        convertGas = getIntent().getStringExtra("convertGas");
        if (getIntent().getStringExtra("toUserId") != null) {
            toUserId = getIntent().getStringExtra("toUserId");
            doSendMsg = true;
        }

        initView();
        initData();
    }

    private void initData() {
        transactionManager = new EthTokenTransactionManager(this);
        //1.加载Credentials
        transactionManager.loadCredentialsASync(filePath, new EthTokenTransactionManager.LoadCredentialsCallBack() {
            @Override
            public void loadResult(boolean isSuccess, final Credentials credentials) {
                if (!isSuccess) {
                    onFailAnim();
                    return;
                }
                //2.获取nonce
//                LogUtils.i("获取nonce", credentials.getAddress());
                transactionManager.getTransactionNonce(myaddress, IPAssetsConstant.CHAIN_ID_TURBOCHAIN, new EthTokenTransactionManager.NonceCallBack() {
                    @Override
                    public void nonceResult(boolean isSuccess, BigInteger nonce) {
                        if (!isSuccess) {
                            onFailAnim();
                            return;
                        }
                        //3.开始转账
//                        LogUtils.i("开始转账", nonce);
                        transactionManager.startEthTransaction(nonce, myaddress,
                                EnvironmentVariable.getProperty(CHAT_USER_ID)
                                , toAddress1, toAccount1,
                                Convert.toWei(count, Convert.Unit.ETHER).toBigInteger(), credentials,
                                EthTokenTransactionManager.ENERGER_COIN_CHAINID,
//                                Convert.toWei(gas, Convert.Unit.ETHER).toBigInteger().divide(Contract.GAS_LIMIT),
                                Convert.toWei(gas, Convert.Unit.GWEI).toBigInteger(),

                                Contract.GAS_LIMIT,
                                new EthTokenTransactionManager.TransactionCallBack<String>() {
                                    @Override
                                    public void transactionResult(boolean isSuccess, String result) {
                                        if (!isSuccess) {
                                            onFailAnim();
                                            return;
                                        }
                                        JSONObject jsonObject = JSONObject.fromObject(result);
                                        animationDrawable.stop();
                                        ivTranferStatus.setBackground(null);
                                        ivTranferStatus.setImageDrawable(ContextCompat.getDrawable(TransferSuccessActivity.this, R.drawable.transfer_success));
                                        tvCount.setText("-" + count);
                                        tvCount.setVisibility(View.VISIBLE);
                                        tvTransStatus.setText(ResStringUtil.getString(R.string.open_planet_transfer_success));
                                        tvCountUnit.setVisibility(View.VISIBLE);
                                        tvCodeIntro.setVisibility(View.VISIBLE);
                                        tvCode.setVisibility(View.VISIBLE);
                                        tvCode.setText(jsonObject.optString("transactionHash", ""));
                                        tvMyAddress.setVisibility(View.VISIBLE);
                                        tvToAddress.setVisibility(View.VISIBLE);
                                        tvMyAddressIntro.setVisibility(View.VISIBLE);
                                        tvToAddressIntro.setVisibility(View.VISIBLE);

                                        tvTime.setVisibility(View.VISIBLE);
                                        tvTimeValue.setVisibility(View.VISIBLE);

                                        try {

                                            Date date = sf1.parse(jsonObject.getString("time"));
                                            transferTime = sf.format(date);
                                            tvTimeValue.setText(transferTime);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        if (doSendMsg) {
                                            sendTransferMsg();
                                            finish();
                                        }
                                    }
                                });
                    }
                });
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
        transactionManager.dispose();
    }

    private void initView() {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ivTranferStatus = (ImageView) findViewById(R.id.transfer_anim);
//        Bitmap bitmap = ((BitmapDrawable) ivTranferStatus.getBackground()).getBitmap();
        animationDrawable = (AnimationDrawable) ivTranferStatus.getBackground();
        animationDrawable.start();
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_transfer_detail));
        tvCode = (TextView) findViewById(R.id.tv_transfer_code);
        tvCode.setText("");
        tvCodeIntro = (TextView) findViewById(R.id.tv_transaction_no);
        tvMyAddress = (TextView) findViewById(R.id.tv_sell_account);
        tvMyAddress.setText(myaddress);
        tvToAddress = (TextView) findViewById(R.id.tv_buy_account);
        tvToAddress.setText(toAddress1);
        tvMyAddressIntro = (TextView) findViewById(R.id.tv_sell_account_intro);
        tvToAddressIntro = (TextView) findViewById(R.id.tv_buy_account_intro);
        tvCount = (TextView) findViewById(R.id.tv_count);
        tvCountUnit = (TextView) findViewById(R.id.tv_count_unit);
        tvTransStatus = (TextView) findViewById(R.id.tv_welcome);
        tvTransStatus.setText(ResStringUtil.getString(R.string.open_planet_transferring));

        tvTime = (TextView) findViewById(R.id.tv_transtime);
        tvTimeValue = (TextView) findViewById(R.id.tv_transtime_value);

    }

    //转账失败
    private void onFailAnim() {
        animationDrawable.stop();
        ivTranferStatus.setBackground(null);
        ivTranferStatus.setImageDrawable(ContextCompat.getDrawable(TransferSuccessActivity.this, R.drawable.transfer_fail));
        tvCodeIntro.setVisibility(View.GONE);
        tvCode.setText("");
        tvTransStatus.setVisibility(View.VISIBLE);
        tvTransStatus.setText(ResStringUtil.getString(R.string.open_planet_transaction_fail));
        tvMyAddress.setVisibility(View.VISIBLE);
        tvToAddress.setVisibility(View.VISIBLE);
        tvMyAddressIntro.setVisibility(View.VISIBLE);
        tvToAddressIntro.setVisibility(View.VISIBLE);
    }

    //发送消息
    private void sendTransferMsg() {
        //    @"{\"receiveUserId\":\"接收方账户（手机号）\",\"receiveWalletAddress\":\"接收方钱包地址\",
        // \"receiveIMUserId\":\"接收方账户（星际ID）\",\"sendUserId\":\"发送方账户\",\"sendWalletAddress\":\"发送方钱包地址\",
        // \"sendIMUserId\":\"发送方账户（星际ID）\",\"money\":\"能量\",\"tradingTime\":\"交易时间s\",\"tradingID\":\"交易ID\"}"

        long currenttime = new Date().getTime();
        Map<String, Object> map = new HashMap<>();
        map.put("receiveUserId", toAccount1);
        map.put("receiveWalletAddress", toAddress1);
        map.put("sendUserId", EnvironmentVariable.getUserName());
        map.put("sendWalletAddress", myaddress);
        map.put("money", count);
        map.put("tradingTime", transferTime);
        map.put("chainId", IPAssetsConstant.CHAIN_ID_TURBOCHAIN);
        map.put("sendIMUserId", EnvironmentVariable.getProperty(CHAT_USER_ID));
        map.put("receiveIMUserId", toUserId);
        map.put("tradingID", tvCode.getText().toString());
        map.put("chainId", IPAssetsConstant.CHAIN_ID_TURBOCHAIN);

        org.json.JSONObject jsonObject = new org.json.JSONObject(map);
        IMStruct002 imStruct002 = new IMStruct002();
        try {
            imStruct002.setBody(jsonObject.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        imStruct002.setTime(currenttime);
        imStruct002.setToUserType(StructFactory.TO_USER_TYPE_PERSONAL);
        imStruct002.setToUserId(Integer.valueOf(toUserId));
        imStruct002.setFromUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        imStruct002.setMessageChildType((short) 8);
        JFMessageManager.getInstance().sendMessage(imStruct002);
        finish();
    }
}
